<template>
  <div class="user-management">
    <header class="header">
      <span class="title">用户管理</span>
      <el-button type="primary" @click="openDialog">添加用户</el-button>
    </header>

    <!-- 新建用户弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        style="width: 1000px;padding: 40px"
        :before-close="handleClose"
    >
      <el-form label-width="80px" label-position="top">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="用户名" :rules="[{ required: true, message: '用户名不能为空', trigger: 'blur' }]">
              <el-input placeholder="请输入用户名" v-model="saveUserForm.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input placeholder="密码" v-model="saveUserForm.password" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input placeholder="请输入真实姓名" v-model="saveUserForm.fullName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input placeholder="请输入手机号" v-model="saveUserForm.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input placeholder="请输入邮箱" v-model="saveUserForm.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建者">
              <el-input v-model="saveUserForm.createBy" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="性别">
              <el-select placeholder="请选择" v-model="saveUserForm.gender">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="账号状态">
              <!--            下拉选框改变事件@change-->
              <el-select placeholder="请选择" v-model="saveUserForm.status">
                <el-option v-for="item in statusArr" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select placeholder="请选择" v-model="saveUserForm.departmentId">
                <el-option v-for="item in departmentArr" :label="item.username" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位">
              <el-select placeholder="请选择" v-model="saveUserForm.positionId">
                <el-option v-for="item in positionArr" :label="item.username" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="角色">
              <el-select
                  v-model="saveUserForm.roles"
                  multiple
                  placeholder="请选择角色"
              >
                <el-option
                    v-for="item in roleArr"
                    :key="item.value"
                    :label="item.lable"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>

    <!--    搜索卡片-->
    <el-card class="search-card">
      <!--      <el-form :inline="true">-->
      <!--        <el-form-item v-for="(field, index) in searchFields" :key="index" :label="field.label">-->
      <!--          <el-input-->
      <!--              placeholder="请输入{{ field.label }}"-->
      <!--              v-model="searchUserForm[field.model]"-->
      <!--              class="search-input"-->
      <!--          />-->
      <!--        </el-form-item>-->
      <!--        <el-form-item>-->
      <!--          <el-button @click="resetSearch" class="reset-button">重置</el-button>-->
      <!--          <el-button type="primary" @click="loadUserList">查询</el-button>-->
      <!--        </el-form-item>-->
      <!--      </el-form>-->
      <el-form :inline="true">
        <el-form-item label="用户搜索">
          <el-input placeholder="请输入用户名" style="width: 220px;" v-model="searchUserForm.username"
                    @keydown.enter="loadUserList"></el-input>
        </el-form-item>
        <el-form-item label="用户状态" style="width: 290px;">
          <el-select placeholder="请选择用户状态" v-model="searchUserForm.status" @change="loadUserList">
            <el-option label="已激活" value="100"></el-option>
            <el-option label="停用" value="110"></el-option>
            <el-option label="初始化" value="120"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadUserList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="UserTableDate" class="user-table">
        <el-table-column type="index" label="编号" width="80" align="center"/>
        <el-table-column prop="username" label="用户名" align="center"/>
        <el-table-column prop="fullName" label="姓名" align="center"/>
        <el-table-column prop="email" label="邮箱地址" align="center"/>
        <el-table-column prop="phone" label="手机号" align="center"/>
        <el-table-column prop="gender" label="性别" align="center" :formatter="genderFormatter"/>
        <el-table-column prop="status" label="账号状态" align="center" :formatter="accountFormatter"/>
        <!--        <el-table-column prop="createTime" label="创建时间" align="center"/>-->
        <!--        <el-table-column prop="updateTime" label="更新时间" align="center"/>-->
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editUser(scope.row.id)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
// import axios from "axios";
import axios from "@/http";
import {ElMessage} from "element-plus";
import router from "@/router";

const dialogTitle = ref('');
const dialogVisible = ref(false);

// 搜索表单
const searchUserForm = ref({
  username: '',
  email: '',
  phone: '',
  departmentId: '',
  positionId: '',
  status: '',
  createBy: '',
  updateBy: ''
});

//用户状态
const statusArr = [
  {label: '已激活', value: '100'},
  {label: '停用', value: '110'},
  {label: '初始化', value: '120'}
];

//部门列表
const departmentArr = ref([
  {username: '研发部', id: 10},
  {username: '市场部', id: 20},
  {username: '运营部', id: 30},
  {username: '销售部', id: 40},
  {username: '财务部', id: 50},
  {username: '行政部', id: 60},
  {username: '其他', id: 70}
]);

//职位
const positionArr = ref([
  {username: '技术经理', id: 100},
  {username: '技术工程师', id: 110},
  {username: '产品经理', id: 120},
  {username: '产品工程师', id: 130},
  {username: '运营经理', id: 140},
  {username: '运营工程师', id: 150},
  {username: '销售经理', id: 160},
  {username: '销售工程师', id: 170},
  {username: '财务经理', id: 180},
])

//角色
const roleArr = ref([
  {lable: '超级管理员', value: "ROLE_ADMIN"},
  {lable: '普通用户', value: "ROLE_USER"}
]);

// 用户列表
const UserTableDate = ref([]);

// 新建用户表单
const userSaveForm = ref({});

// 表单字段配置
//定义对象用来保存表单中的员工数据
const saveUserForm = ref({
  id: null,
  username: '',
  password: '',
  phone: '',
  email: '',
  gender: '',
  fullName: '',
  departmentId: '',
  positionId: '',
  createBy: '',
  roles:''
});

// 搜索字段配置
const searchFields = [
  {label: "用户名", model: "username"},
  // {label: "邮箱", model: "email"},
  {label: "手机号", model: "phone"},
  // {label: "部门ID", model: "departmentId"},
  // {label: "职位ID", model: "positionId"},
  {label: "账号状态", model: "status"}
  // {label: "创建人", model: "createBy"},
  // {label: "更新人", model: "updateBy"}
];

// 获取用户列表
const loadUserList = () => {
  axios.post('/oa/user/userlist', searchUserForm.value).then(response => {
    console.log("获取用户列表response", response);
    debugger;
    if (response.data.code === 20000) {
      UserTableDate.value = response.data.data;
    } else {
      ElMessage.error("会话过期，请重新登录！");
    }
  });
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchUserForm.value).forEach(key => searchUserForm.value[key] = '');
  loadUserList();
};
const userInfo = getUser();
// 打开对话框
const openDialog = () => {
  saveUserForm.value = {};
  dialogVisible.value = true;
  dialogTitle.value = '添加用户';
  saveUserForm.value.createBy = userInfo ? userInfo.username : '管理员';
  console.log("userInfo.username", userInfo.username);
  console.log("saveUserForm", saveUserForm);
};

// 关闭对话框
const handleClose = () => {
  if (confirm('确定要关闭此弹窗?')) {
    dialogVisible.value = false;
    userSaveForm.value = {};
    loadUserList();
  }
};

// 性别格式化
const genderFormatter = (row, column, cellValue) => (cellValue === 0 ? '女' : '男');

// 账号状态格式化
const accountFormatter = (row, column, cellValue) => (cellValue === 100 ? '正常' : '停用');

// 保存用户
const saveUser = () => {
  if (saveUserForm.value.id != null) {
    axios.post('/oa/user/edit', saveUserForm.value).then(response => {
      console.log("编辑用户saveUserForm.value", saveUserForm.value);
      if (response.data.code === 20000) {
        console.log("编辑用户response", response);
        ElMessage.success('编辑用户成功');
        dialogVisible.value = false;
        // 重新加载用户列表
        loadUserList();
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  } else {
    console.log("保存用户saveUserForm.value", saveUserForm.value);
    axios.post('/oa/user/add', saveUserForm.value).then(response => {
      console.log("保存用户response", response);
      console.log("saveUserForm.value", saveUserForm.value);
      if (response.data.code === 20000) {
        ElMessage.success("保存成功");
        saveUserForm.value = {};
        dialogVisible.value = false;
        loadUserList();
        user();
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  }
};

//点击用户表格的"编辑"按钮
const editUser = (id) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑用户信息';
  debugger;
  console.log("编辑用户信息,userId", id);
  //需要根据当前用户id查询该用户的详细信息，回显在弹窗表单中
  axios.get('/oa/user/detail/' + id).then((response) => {
    if (response.data.code == 20000) {
      //注意：后端返回的是List<UserVo> 所以查一条数据的话拿的是集合的第一个元素data[0]
      saveUserForm.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 删除用户
const deleteUser = (id) => {
  if (confirm('确定要删除此用户?')) {
    axios.post('/oa/user/delete/' + id).then(response => {
      if (response.data.code === 20000) {
        ElMessage.success("删除成功");
        loadUserList();
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  }
};


const user = () => {
  axios.get('/oa/user/addNum').then((response)=>{
  })
}

onMounted(() => {
  loadUserList();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.user-dialog {
  width: 800px;
  padding: 30px;
}

.dialog-form {
  max-width: 600px;
}

.search-card {
  margin: 20px 0;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 200px;
}

.user-table {
  border-radius: 5px;
  overflow: hidden;
}

.user-table .el-table th {
  background-color: #eaeaea;
}

.reset-button {
  margin-right: 10px;
}
</style>
